import Vue from "vue";
import VueRouter from "vue-router";
import Config from '../config.js'
import routes from './router.js'
import service from '../service/index.js'
Vue.use(VueRouter);

const router = new VueRouter({
  routes
});
router.beforeEach(({meta,path}, from, next) => {
	//当返回到顶层时,将当前路径设置为下一个返回路径
	var isLogin = window.localStorage.getItem("2_isLogin");
	if(path.indexOf("/customerDetails") == 0 && path.indexOf("/templateMessage") > 0 && !isLogin) {
		return next({
			path: '/login?redirectUrl='+path
		});
	}
	if(path.indexOf("/premisesDetail") == 0 && (from.path.indexOf("/premisesDetail")) == 0){
		return next({
			path:'/premisesList'
		})
	}
	 if("/forgetPassword" == path || path.indexOf("/sharePremisesDetail") == 0){
        return next();
    }

	if("/index" == path || "/" == path || "/app" == path || "/login" == path ){
		//当返回至 /app 时,往前走一步,跳转到首页
		if("/app" == path && isLogin==true){
			window.history.forward(1);
		}
		if("/login" == path && (isLogin==true || isLogin=="true")){
			return next({
				path: '/index'
			});
		}
		// history.pushState(null, null, document.URL);
	}

	if((!isLogin || isLogin == 'null' || isLogin==false || isLogin=="false")&& path !== '/login') {
		return next({
			path: '/login'
		})
	}
	next();
	var isLogin = window.localStorage.getItem("2_isLogin");
	if(isLogin == 'true'){
		var url = Config.apiUrl + "/api/getOptAuth";
		var body = {};
		// body.params = {resourcesType:2}
		body.params = {}
		service.post(url, body).then((response) => {
			var data = response.body.resData;
		   	var result=data.result;
		   	var errorMsg = data.resultMsg;
		   	if(result=="1"){
				window.sessionStorage.setItem("2_resources",JSON.stringify(data.list));
		   	}
		});
	}
	
});

export default router;
